package mammuthus.controller.docker

import org.joda.time.DateTime
import mammuthus.protocal.DockerInstanceDetail

/**
 * 5/12/15 WilliamZhu(allwefantasy@gmail.com)
 */
trait DockerTaskHelper {
  this: DockerTaskController =>

  def filterStatus(status: String) = {
    param("status", "all") match {
      case "running" => status.startsWith("up")
      case "exited" => status.startsWith("exited (0)")
      case "exception" => status.startsWith("exited") && !status.contains("exited (0)")
      case _ => true
    }
  }

  def formatStatus(_status: String):String = {
    val status = _status.toLowerCase
    if(status.startsWith("up")) return "running"
    if(status.startsWith("exited (0)")) return "exited"
    if(status.startsWith("exited") && !status.contains("exited (0)")) return "exception"
    return ""
  }

  def formatContainerDetail(ist: DockerInstanceDetail) = {
    Map(
      "hostName" -> ist.hostName,
      "id" -> ist.id.take(12),
      "names" -> ist.names.map(f => f.substring(1, f.length)).mkString(","),
      "image" -> ist.image,
      "create" -> new DateTime(ist.create).toString(param("timeFormat", "yyyyMMdd-hh:MM:ss")),
      "status" -> formatStatus(ist.status),
      "command" -> ist.command,
      "ip" -> akkaMaster.findIpByHost(ist.names.map(f => f.substring(1, f.length)).mkString(",")),
      "ports" -> ist.ports.map(f => s"""${f.ip}:${f.privatePort} => ${f.publicPort} ${f.ctype}""").mkString(",")
    )
  }

}
